from django.contrib import admin
from django.contrib.auth.models import User

from .models import Book, BorrowRecord
from import_export import resources, fields, widgets
from import_export.admin import ImportExportModelAdmin
from import_export.formats import base_formats
from import_export.widgets import ForeignKeyWidget


class BookResource(resources.ModelResource):
    id = fields.Field(attribute='id', column_name='ID')
    title = fields.Field(attribute='title', column_name='书名')
    author = fields.Field(attribute='author', column_name='作者')
    publisher = fields.Field(attribute='publisher', column_name='出版社')
    publish_date = fields.Field(
        attribute='publish_date',
        column_name='出版日期',
        widget=widgets.DateWidget(format='%Y/%m/%d')  # 根据实际格式调整
    )
    isbn = fields.Field(attribute='isbn', column_name='ISBN')
    category = fields.Field(attribute='category', column_name='分类')
    status = fields.Field(attribute='status', column_name='状态')
    description = fields.Field(attribute='description', column_name='描述')



    class Meta:
        model = Book
        import_id_fields = ('isbn',)
        skip_unchanged = True

    def before_import_row(self, row, **kwargs):
        """确保日期格式正确"""
        date_str = row.get('出版日期')
        if date_str:
            # 统一转换为YYYY-MM-DD格式
            if '/' in date_str:
                parts = date_str.split('/')
                row['出版日期'] = f"{parts[0]}-{parts[1].zfill(2)}-{parts[2].zfill(2)}"
class BorrowRecordResource(resources.ModelResource):
    book = fields.Field(
        column_name='book',
        attribute='book',
        widget=ForeignKeyWidget(Book, 'id')
    )

    borrower = fields.Field(
        column_name='borrower',
        attribute='borrower',
        widget=ForeignKeyWidget(User, 'id')
    )

    class Meta:
        model = BorrowRecord
        import_id_fields = ('id',)
        skip_unchanged = True
        report_skipped = True
        fields = ('id', 'book', 'borrower', 'borrow_date',
                 'return_date', 'due_date', 'is_returned')

class BookAdmin(ImportExportModelAdmin):
    formats = (base_formats.XLSX, base_formats.CSV, base_formats.JSON)
    resource_class = BookResource
    list_display = ('title', 'author', 'publisher', 'category', 'status')
    list_filter = ('category', 'status')
    search_fields = ('title', 'author', 'isbn')
    date_hierarchy = 'publish_date'

class BorrowRecordAdmin(ImportExportModelAdmin):
    formats = (base_formats.XLSX, base_formats.CSV, base_formats.JSON)
    resource_class = BorrowRecordResource
    list_display = ('book', 'borrower', 'borrow_date', 'due_date', 'is_returned')
    list_filter = ('is_returned', 'borrow_date')
    search_fields = ('book__title', 'borrower__username')
    date_hierarchy = 'borrow_date'

admin.site.register(Book, BookAdmin)
admin.site.register(BorrowRecord, BorrowRecordAdmin)